<?php
/**
 * CreateTime: 2023/8/17 17:06
 */

namespace App\Func;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Models\LatterCache\MeSendLatterCacheModel;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCaseLawLetterModel;
use App\Scopes\MediationStaffScope;
use App\Tools\DocxGenerator\FormatDocx;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use setasign\Fpdi\Fpdi;

class LetterFunc
{
    public function downLoadZZLetter($sendLetterCacheId){
        $cacheModel = new MeSendLatterCacheModel();
        $cacheInfo = $cacheModel
            ->select([
                'send_letter_cache_id',
                'letter_ids',
            ])
            ->where('type',2)
            ->where('send_letter_cache_id',$sendLetterCacheId)->first();
        if(!$cacheInfo){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "当前纸质函生成不存在",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }

        // 校验当前组内案件是否全部已发函
        $ids = explode(',',$cacheInfo['letter_ids']);
        $allCount = count($ids);

        // 创建临时表
        DB::statement('CREATE TEMPORARY TABLE cy_temp_ids (fa_id INT, INDEX idx_fa_id (fa_id))');
        // 处理临时表中的数据
        $newArray = array_map(function($value) {
            return ['fa_id' => $value];
        }, $ids);
        // 插入数据到临时表
        DB::table('temp_ids')->insert($newArray);
        $lawCaseModel = new MeLawCase();
        $lawCaseList = $lawCaseModel->select([
            'law_case_id as lawCaseId',
            'loans_remaining_principal as money'
        ])
        ->join('temp_ids as temp','law_case_id','temp.fa_id')
        ->where('is_send_zz_law_letter',2)
        ->where('status',1) // 案件必须是正常未删除
        ->get()
        ->toArray();
        if(count($lawCaseList)!=$allCount){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "当前批次纸质函未生成完毕",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }








    }




    private function getLetterNumbers($clientId){
        // 记录缓存的客户端和 code 数据
        $clientCodeList = Redis::get('mediation_client_code_list');
        if($clientCodeList === null){
            $clientModel = new MeClientModel();
            $clientCodeArray = array_column($clientModel
                ->withoutGlobalScope(MediationStaffScope::class)
                ->select(['client_id','client_code'])
                ->get()->toArray(),'client_code','client_id');
            $clientCodeList = json_encode($clientCodeArray,256);
            Redis::set('mediation_client_code_list', $clientCodeList);
        }
        $clientCodeMap =  json_decode($clientCodeList,true);
        $code = $clientCodeMap[$clientId];
        // 这里需要一个定时任务清理器
        $count = Redis::get('law_letter_count_dz'.date("Y-m").$code);
        if($count === null){
            $lawCaseLetterModel = new MeLawCaseLawLetterModel();
            $count = $lawCaseLetterModel->withoutGlobalScope(MediationStaffScope::class)->where('client_id',$clientId)->where('created_time','>=',date("Y-m-d",time()))->count();
            Redis::set('law_letter_count_dz'.date("Y-m").$code, $count);
        }
        $number = $count + 1;
        return [
            'count' => $number,
            'code' => $code
        ];
    }


    public function createdWord($template_data_json_str,$clientTempFileName,$canDump = true){
        // FpdiCLASS
        $pdf = new Fpdi();
        // 路径
        $appPath= storage_path("app");
        $appTempPath= storage_path("app/lawLatter");

        $path = storage_path('app/defaultTemplate/'.$clientTempFileName);
        if($canDump){
            dump($path);
        }

        if(!is_file($path)){
            if($canDump){
                dump("文件不存在");
            }
            return false;
        }
        // 根据客户名称和类型生成文件名
        $fileName = "law_letter_".time();
        $fileExt = "docx";
        $fileUrl = FormatDocx::formatClientEvaluationTemplateReplace(
            $template_data_json_str,
            $path,
            [
                "file_name"=> $fileName,
                "create_at"=> time(),
                "file_ext"=> $fileExt,
            ]
        );
        if($canDump){
            dump($fileUrl);

        }
        /**
         * "oldPath" => "/node/docgen/law_letter_1686821831.pdf"
         * "newPath" => "templateFormat/20230615/law_letter_1686821831.pdf"
         */
        $path = FormatDocx::wordToPdf(
            $fileUrl,
            $fileName.".".$fileExt
        );
        if($canDump){
            dump($path);

        }

        // 为当前PDF添加水印
        $pageCount = $pdf->setSourceFile($appPath.DIRECTORY_SEPARATOR.$path['newPath']);
        //遍历所有页面
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++){
            //导入页面
            $templateId = $pdf->importPage($pageNo);
            //获取导入页面的大小
            $size = $pdf->getTemplateSize($templateId);
            //创建页面（横向或纵向取决于导入的页面大小）
            if ($size['width'] > $size['height']){
                $pdf->AddPage('L', array($size['width'], $size['height']));
            }else {
                $pdf->AddPage('P', array($size['width'], $size['height']));
            }
            //使用导入的页面
            $pdf->useTemplate($templateId);
            if(false){//文字水印
                //设置字体
                //$pdf->SetFont('Arial','B','24');
                $family = ['courier', 'helvetica', 'times', 'symbol', 'zapfdingbats'];
                $pdf->SetFont('helvetica','U','50');
                //设置位置 - 加在中间位置
                $center_x = $size['width']/2;
                $center_y = $size['height']/2;
                $pdf->SetXY($center_x, $center_y);
                //写入水印 - 中文会乱码 建议使用中文图片
                $pdf->Write(7, 'ROOT_ICO');
            }else{//图片水印
                $center_x = $size['width']/2 - 40;$center_y = $size['height']/2;
                $pdf->image(__DIR__."/defaultWatermarkChaoYueLaw.png", 0, 0,210);//全屏背景水印
            }
        }

        // 输出pdf
        // I输出output，D下载download，F保存file_put_contents，S返回return
        $pdfWaterName = basename($path['newPath']);
        $pdfWaterArray = explode('.',$pdfWaterName);
        $pdfReqName = $pdfWaterArray[0].'_watermark.'.$pdfWaterArray[1];
        $waterPdfPath = str_replace($pdfWaterName, $pdfReqName, $path['newPath']);
        // 水印完整路径
        $waterPdfPathExt = $appPath.DIRECTORY_SEPARATOR.$waterPdfPath;
        $pdfContent = $pdf->Output('S');
        $flag = file_put_contents($waterPdfPathExt, $pdfContent);
        if(!is_dir($appTempPath)){
            mkdir($appTempPath);
            (new SystemFunc())->setFileOwnerAndGroup($appTempPath,'www','www');
            // \chown($appTempPath,'www');
        }else{
            (new SystemFunc())->setFileOwnerAndGroup($appTempPath,'www','www');

            // \chown($appTempPath,'www');
        }

        if(!is_dir($appTempPath.DIRECTORY_SEPARATOR.date("Ymd"))){
            mkdir($appTempPath.DIRECTORY_SEPARATOR.date("Ymd"));
            // \chown($appTempPath.DIRECTORY_SEPARATOR.date("Ymd"),'www');
            (new SystemFunc())->setFileOwnerAndGroup($appTempPath.DIRECTORY_SEPARATOR.date("Ymd"),'www','www');

        }else{
            (new SystemFunc())->setFileOwnerAndGroup($appTempPath.DIRECTORY_SEPARATOR.date("Ymd"),'www','www');
            // \chown($appTempPath.DIRECTORY_SEPARATOR.date("Ymd"),'www');
        }
        // 计算文件唯一hash值

        $hash = hash_file('sha256',$waterPdfPathExt);
        $pdfToImageInfo = CoverFunc::coverPdfToPng($waterPdfPathExt,$appTempPath.DIRECTORY_SEPARATOR.date("Ymd"));

        return [
            'pdf_path' => $path['newPath'],
            'pdf_water_path' => $waterPdfPath,
            'pdf_hash' => $hash,
            'image_group' => str_replace($appPath.DIRECTORY_SEPARATOR,'',$pdfToImageInfo['image_output_path'])
        ];
    }


    public function  setDefaultFiledByClient($clientId,$data,$tCode){
        $codeInfo = $this->getLetterNumbers($clientId);
        switch ($clientId){
            case 16:
                $time = time();
                $data['now_year'] = date("Y",$time);
                $data['now_month'] = str_pad(date("m"), 2, '0', STR_PAD_LEFT);
                $data['now_day'] = str_pad(date("d",$time), 2, '0', STR_PAD_LEFT);
                if($codeInfo['count']<999){
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-$tCode-".str_pad($codeInfo['count'], 4, '0', STR_PAD_LEFT);;
                }else{
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-$tCode-".$codeInfo['count'];
                }
                return $data;
            case 17:
                $time = time();
                $data['now_month'] = str_pad(date("m"), 2, '0', STR_PAD_LEFT);
                $data['end_time'] = date("Y年m月d日",$time);
                if($codeInfo['count']<999){
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-$tCode-".str_pad($codeInfo['count'], 4, '0', STR_PAD_LEFT);
                }else{
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-$tCode-".$codeInfo['count'];
                }
                $data['make_date'] = $data['end_time'];
                return $data;
            default:
                $time = time();
                $data['now_month'] = str_pad(date("m"), 2, '0', STR_PAD_LEFT);
                $data['end_time'] = date("Y年m月d日",$time);
                if($codeInfo['count']<999){
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-$tCode-".str_pad($codeInfo['count'], 4, '0', STR_PAD_LEFT);
                }else{
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-$tCode-".$codeInfo['count'];
                }
                $data['make_date'] = date("Y年m月d日",$time);
                return $data;
        }
    }
}